import os
import sys

from ansible.parsing.dataloader import DataLoader
from ansible.inventory.manager import InventoryManager


def get_group_host(group_id):
  host_list = []
  inventory_file_name = '/etc/ansible/hosts'
  data_loader = DataLoader()
  inventory = InventoryManager(loader = data_loader, sources=[inventory_file_name])

  for key in inventory.get_groups_dict()[group_id]:
    host_list.append(key)
  return host_list

def get_group_host_host_name(group_id):
  host_list = []
  inventory_file_name = '/etc/ansible/hosts'
  data_loader = DataLoader()
  inventory = InventoryManager(loader = data_loader, sources=[inventory_file_name])

  for key in inventory.get_groups_dict()[group_id]:
    host = inventory.get_host(key)
    vars=host.get_vars()
    hostname=vars['hostname']
    iphostname = []
    iphostname.append(key)
    iphostname.append(hostname)
    host_list.append(iphostname)

  return host_list


if len(sys.argv) == 2:
  group_name=str(sys.argv[1])
  for i, val in enumerate(get_group_host(group_name)):
    print(val)

if len(sys.argv) == 3:
  group_name=str(sys.argv[1])
  for host_list in get_group_host_host_name(group_name):
    for i, host in enumerate(host_list):
      if i == 0:
        print(host + " ", end="")
      else:
        print(host)

